import 'package:flutter_bloc/flutter_bloc.dart';
import 'auth_event.dart';
import 'auth_state.dart';
import 'package:awak/common/repository/user_repository.dart';
import 'package:awak/common/models/user.dart';
import 'package:awak/common/models/comment.dart';
import 'package:awak/common/models/topic.dart';
import 'package:awak/common/models/room.dart';
import 'package:awak/common/repository/room_repository.dart';
import 'package:awak/common/repository/comment_repository.dart';
import 'package:awak/common/repository/topic_repository.dart';
import 'package:awak/common/repository/content_repository.dart';
import 'package:awak/common/repository/review_repository.dart';
import 'package:awak/common/repository/chat_repository.dart';
import 'package:awak/common/repository/friendship_repository.dart';
import 'package:awak/common/repository/plan_repository.dart';
import 'package:awak/common/repository/today_goal_repository.dart';

class AwakBloc extends Bloc<AwakEvent, AwakState> {
  final UserRepository userRepository;
  final RoomRepository roomRepository;
  final CommentRepository commentRepository;
  final TopicRepository topicRepository;
  final ContentRepository contentRepository;
  final ReviewRepository reviewRepository;
  final ChatRepository chatRepository;
  final FriendshipRepository friendshipRepository;
  final PlanRepository planRepository;
  final TodayGoalRepository todayGoalRepository;

  AwakBloc(this.userRepository, this.roomRepository, this.commentRepository, this.topicRepository, this.contentRepository, this.reviewRepository, this.chatRepository, this.friendshipRepository, this.planRepository, this.todayGoalRepository) : super(AwakInitial()) {
    // 登录
    on<LoginEvent>((event, emit) async {
      emit(AwakLoading());
      final user = await userRepository.login(event.username, event.password);
      if (user != null) {
        userRepository.currentUser = user;
        emit(AwakSuccess(user));
      } else {
        emit(AwakFailure('username or password error'));
      }
    });

    // 注册
    on<RegisterEvent>((event, emit) async {
      emit(AwakLoading());
      final exist = await userRepository.getUserByUsername(event.username);
      if (exist != null) {
        emit(AwakFailure('username already exists'));
        return;
      }
      final user = User(username: event.username, password: event.password);
      await userRepository.register(user);
      emit(AwakSuccess(user));
    });

    // 退出登录
    on<LogoutEvent>((event, emit) async {
      await userRepository.logout();
      emit(AwakInitial());
    });

    // 删除用户
    on<DeleteUserEvent>((event, emit) async {
      await userRepository.deleteUser();
      emit(AwakInitial());
    });

    // 获取所有房间
    on<FetchRoomsEvent>((event, emit) async {
      emit(RoomLoading());
      try {
        final rooms = await roomRepository.getAllRooms();
        // 保持之前的topics数据
        List<Topic>? existingTopics;
        if (state is TopicsLoaded) {
          existingTopics = (state as TopicsLoaded).topics;
        } else if (state is RoomsLoaded) {
          existingTopics = (state as RoomsLoaded).topics;
        }
        emit(RoomsLoaded(rooms, currentUser: userRepository.currentUser, topics: existingTopics));
      } catch (e) {
        emit(RoomFailure('Failed to get rooms'));
      }
    });
    // 添加房间
    on<AddRoomEvent>((event, emit) async {
      emit(RoomLoading());
      try {
        await roomRepository.addRoom(event.room);
        if (userRepository.currentUser != null) {
          emit(AwakSuccess(userRepository.currentUser!));
        } else {
          emit(AwakSuccess(event.room as dynamic));
        }
      } catch (e) {
        emit(RoomFailure('Failed to add room'));
      }
    });
    // 删除房间
    on<DeleteRoomEvent>((event, emit) async {
      emit(RoomLoading());
      try {
        await roomRepository.deleteRoom(event.id);
        final rooms = await roomRepository.getAllRooms();
        emit(RoomsLoaded(rooms));
      } catch (e) {
        emit(RoomFailure('Failed to delete room'));
      }
    });
    // 更新房间
    on<UpdateRoomEvent>((event, emit) async {
      emit(RoomLoading());
      try {
        await roomRepository.updateRoom(event.room);
        final rooms = await roomRepository.getAllRooms();
        emit(RoomsLoaded(rooms));
      } catch (e) {
        emit(RoomFailure('Failed to update room'));
      }
    });

    // 获取指定房间的评论
    on<FetchCommentsByRoomIdEvent>((event, emit) async {
      emit(CommentLoading());
      try {
        final comments = await commentRepository.getCommentsByRoomId(event.roomId);
        emit(CommentsLoaded(comments, currentUser: userRepository.currentUser));
      } catch (e) {
        emit(CommentFailure('Failed to get comments'));
      }
    });

    // 添加评论
    on<AddCommentEvent>((event, emit) async {
      emit(CommentLoading());
      try {
        await commentRepository.addComment(event.comment);
        final comments = await commentRepository.getCommentsByRoomId(event.comment.roomId);
        emit(CommentsLoaded(comments, currentUser: userRepository.currentUser));
      } catch (e) {
        emit(CommentFailure('Failed to add comment'));
      }
    });

    // 删除评论
    on<DeleteCommentEvent>((event, emit) async {
      emit(CommentLoading());
      try {
        await commentRepository.deleteComment(event.id);
        emit(CommentSuccess(Comment(content: '', userId: 0, roomId: 0)));
      } catch (e) {
        emit(CommentFailure('Failed to delete comment'));
      }
    });

    // 检查当前登录用户
    on<CheckCurrentUserEvent>((event, emit) async {
      if (userRepository.currentUser != null) {
        emit(AwakSuccess(userRepository.currentUser!));
      }
    });

    // 获取所有主题
    on<FetchTopicsEvent>((event, emit) async {
      emit(TopicLoading());
      try {
        final topics = await topicRepository.getAllTopics();
        // 保持之前的rooms数据
        List<Room>? existingRooms;
        if (state is RoomsLoaded) {
          existingRooms = (state as RoomsLoaded).rooms;
        } else if (state is TopicsLoaded) {
          existingRooms = (state as TopicsLoaded).rooms;
        }
        emit(TopicsLoaded(topics, currentUser: userRepository.currentUser, rooms: existingRooms));
      } catch (e) {
        emit(TopicFailure('Failed to get topics'));
      }
    });

    // 根据标签获取主题
    on<FetchTopicByLabelEvent>((event, emit) async {
      emit(TopicLoading());
      try {
        final topic = await topicRepository.getTopicByLabel(event.label);
        emit(TopicLoaded(topic, currentUser: userRepository.currentUser));
      } catch (e) {
        emit(TopicFailure('Failed to get topic'));
      }
    });

    // 获取所有内容
    on<FetchContentsEvent>((event, emit) async {
      emit(ContentLoading());
      try {
        final contents = await contentRepository.getAllContents();
        emit(ContentsLoaded(contents, currentUser: userRepository.currentUser));
      } catch (e) {
        emit(ContentFailure('Failed to get contents'));
      }
    });

    // 获取指定内容的评论
    on<FetchReviewsByContentIdEvent>((event, emit) async {
      emit(ReviewLoading());
      try {
        final reviews = await reviewRepository.getReviewsByContentId(event.contentId);
        emit(ReviewsLoaded(reviews, currentUser: userRepository.currentUser));
      } catch (e) {
        emit(ReviewFailure('Failed to fetch reviews: $e'));
      }
    });

    // 添加评论
    on<AddReviewEvent>((event, emit) async {
      try {
        final reviewId = await reviewRepository.addReview(event.review);
        final newReview = event.review.copyWith(id: reviewId);
        emit(ReviewAdded(newReview));

        // 重新获取评论列表
        final reviews = await reviewRepository.getReviewsByContentId(event.review.contentId);
        emit(ReviewsLoaded(reviews, currentUser: userRepository.currentUser));
      } catch (e) {
        emit(ReviewFailure('Failed to add review: $e'));
      }
    });

    // 更新评论
    on<UpdateReviewEvent>((event, emit) async {
      try {
        await reviewRepository.updateReview(event.review);
        emit(ReviewUpdated(event.review));

        // 重新获取评论列表
        final reviews = await reviewRepository.getReviewsByContentId(event.review.contentId);
        emit(ReviewsLoaded(reviews, currentUser: userRepository.currentUser));
      } catch (e) {
        emit(ReviewFailure('Failed to update review: $e'));
      }
    });

    // 删除评论
    on<DeleteReviewEvent>((event, emit) async {
      try {
        await reviewRepository.deleteReview(event.id);
        emit(ReviewDeleted(event.id));
      } catch (e) {
        emit(ReviewFailure('Failed to delete review: $e'));
      }
    });

    // 获取两个用户之间的聊天记录
    on<FetchChatMessagesEvent>((event, emit) async {
      emit(ChatLoading());
      try {
        final messages = await chatRepository.getChatMessages(event.userId1, event.userId2);

        // 获取当前用户和对方用户信息
        final currentUser = userRepository.currentUser;
        User? otherUser;

        if (currentUser?.id == event.userId1) {
          otherUser = await userRepository.getUserById(event.userId2);
        } else {
          otherUser = await userRepository.getUserById(event.userId1);
        }

        emit(ChatMessagesLoaded(messages, currentUser: currentUser, otherUser: otherUser));
      } catch (e) {
        emit(ChatFailure('Failed to load chat messages: $e'));
      }
    });

    // 发送聊天消息
    on<SendChatMessageEvent>((event, emit) async {
      try {
        await chatRepository.sendMessage(event.chat);
        emit(ChatMessageSent(event.chat));

        // 重新加载聊天记录
        final messages = await chatRepository.getChatMessages(
          event.chat.sendUserId,
          event.chat.acceptUserId
        );

        final currentUser = userRepository.currentUser;
        User? otherUser;

        if (currentUser?.id == event.chat.sendUserId) {
          otherUser = await userRepository.getUserById(event.chat.acceptUserId);
        } else {
          otherUser = await userRepository.getUserById(event.chat.sendUserId);
        }

        emit(ChatMessagesLoaded(messages, currentUser: currentUser, otherUser: otherUser));
      } catch (e) {
        emit(ChatFailure('Failed to send message: $e'));
      }
    });

    // 删除聊天消息
    on<DeleteChatMessageEvent>((event, emit) async {
      try {
        await chatRepository.deleteMessage(event.chatId);
        emit(ChatMessageDeleted(event.chatId));
      } catch (e) {
        emit(ChatFailure('Failed to delete message: $e'));
      }
    });

    // 清空两个用户之间的聊天记录
    on<ClearChatBetweenUsersEvent>((event, emit) async {
      try {
        await chatRepository.deleteChatBetweenUsers(event.userId1, event.userId2);
        emit(ChatCleared());

        // 重新加载空的聊天记录
        emit(ChatMessagesLoaded([], currentUser: userRepository.currentUser));
      } catch (e) {
        emit(ChatFailure('Failed to clear chat: $e'));
      }
    });

    // 标记消息为已读
    on<MarkMessagesAsReadEvent>((event, emit) async {
      try {
        await chatRepository.markMessagesAsRead(event.currentUserId, event.otherUserId);
      } catch (e) {
        // 静默处理错误，不影响用户体验
        print('Failed to mark messages as read: $e');
      }
    });

    // 添加好友
    on<AddFriendEvent>((event, emit) async {
      emit(FriendshipLoading());
      try {
        await friendshipRepository.addFriend(event.userId, event.friendId);
        emit(FriendAdded('added as a friend successfully!'));
      } catch (e) {
        if (e.toString().contains('Already friends')) {
          emit(FriendshipFailure('Already friends'));
        } else {
          emit(FriendshipFailure('Failed to add friend: $e'));
        }
      }
    });

    // 删除好友
    on<RemoveFriendEvent>((event, emit) async {
      emit(FriendshipLoading());
      try {
        await friendshipRepository.removeFriend(event.userId, event.friendId);
        emit(FriendRemoved('successfully delete!'));
      } catch (e) {
        emit(FriendshipFailure('Failed to remove friend: $e'));
      }
    });

    // 获取好友列表
    on<FetchFriendsEvent>((event, emit) async {
      emit(FriendshipLoading());
      try {
        final friends = await friendshipRepository.getFriends(event.userId);
        emit(FriendsLoaded(friends, currentUser: userRepository.currentUser));
      } catch (e) {
        emit(FriendshipFailure('Failed to load friends: $e'));
      }
    });

    // 检查好友关系
    on<CheckFriendshipEvent>((event, emit) async {
      try {
        final isFriend = await friendshipRepository.isFriend(event.userId, event.friendId);
        emit(FriendshipChecked(isFriend));
      } catch (e) {
        emit(FriendshipFailure('Failed to check friendship: $e'));
      }
    });

    // 创建计划
    on<CreatePlanEvent>((event, emit) async {
      emit(PlanLoading());
      try {
        await planRepository.createPlan(event.plan);
        emit(PlanCreated(event.plan));
      } catch (e) {
        emit(PlanFailure('Failed to create plan: $e'));
      }
    });

    // 获取用户的所有计划
    on<FetchPlansEvent>((event, emit) async {
      emit(PlanLoading());
      try {
        final plans = await planRepository.getPlansByUserId(event.userId);
        emit(PlansLoaded(plans));
      } catch (e) {
        emit(PlanFailure('Failed to load plans: $e'));
      }
    });

    // 获取今天未完成的计划
    on<FetchTodayUncompletedPlansEvent>((event, emit) async {
      try {
        final plans = await planRepository.getTodayUncompletedPlans(event.userId);
        emit(TodayUncompletedPlansLoaded(plans));
      } catch (e) {
        emit(PlanFailure('Failed to load today\'s uncompleted plans: $e'));
      }
    });

    // 获取本周的计划
    on<FetchThisWeekPlansEvent>((event, emit) async {
      try {
        final plans = await planRepository.getThisWeekPlans(event.userId);
        emit(ThisWeekPlansLoaded(plans));
      } catch (e) {
        emit(PlanFailure('Failed to load this week\'s plans: $e'));
      }
    });

    // 获取未开始的计划
    on<FetchNotStartedPlansEvent>((event, emit) async {
      try {
        final plans = await planRepository.getNotStartedPlans(event.userId);
        emit(NotStartedPlansLoaded(plans));
      } catch (e) {
        emit(PlanFailure('Failed to load not started plans: $e'));
      }
    });

    // 更新计划状态
    on<UpdatePlanStateEvent>((event, emit) async {
      try {
        await planRepository.updatePlanState(event.planId, event.state);
        emit(PlanStateUpdated(event.planId, event.state));
      } catch (e) {
        emit(PlanFailure('Failed to update plan state: $e'));
      }
    });

    // 更新计划时间
    on<UpdatePlanTimeEvent>((event, emit) async {
      try {
        await planRepository.updatePlan(event.plan);
        emit(PlanTimeUpdated(event.plan));
      } catch (e) {
        emit(PlanFailure('Failed to update plan time: $e'));
      }
    });

    // 更新超时计划状态
    on<UpdateExpiredPlansEvent>((event, emit) async {
      try {
        await planRepository.updateExpiredPlansToFailed(event.userId);
        emit(ExpiredPlansUpdated());
      } catch (e) {
        emit(PlanFailure('Failed to update expired plans: $e'));
      }
    });

    // 删除计划
    on<DeletePlanEvent>((event, emit) async {
      try {
        await planRepository.deletePlan(event.planId);
        emit(PlanDeleted(event.planId));
      } catch (e) {
        emit(PlanFailure('Failed to delete plan: $e'));
      }
    });

    // 获取过去30天的历史计划
    on<FetchLast30DaysPlansEvent>((event, emit) async {
      try {
        final plans = await planRepository.getLast30DaysPlans(event.userId);
        emit(Last30DaysPlansLoaded(plans));
      } catch (e) {
        emit(PlanFailure('Failed to load last 30 days plans: $e'));
      }
    });

    // 创建今日目标
    on<CreateTodayGoalEvent>((event, emit) async {
      emit(TodayGoalLoading());
      try {
        await todayGoalRepository.createTodayGoal(event.todayGoal);
        emit(TodayGoalCreated(event.todayGoal));
      } catch (e) {
        emit(TodayGoalFailure('Failed to create today goal: $e'));
      }
    });

    // 获取用户的今日目标
    on<FetchTodayGoalsEvent>((event, emit) async {
      try {
        final todayGoals = await todayGoalRepository.getTodayGoalsByUserId(event.userId);
        emit(TodayGoalsLoaded(todayGoals));
      } catch (e) {
        emit(TodayGoalFailure('Failed to load today goals: $e'));
      }
    });

    // 删除今日目标
    on<DeleteTodayGoalEvent>((event, emit) async {
      try {
        await todayGoalRepository.deleteTodayGoal(event.goalId);
        emit(TodayGoalDeleted(event.goalId));
      } catch (e) {
        emit(TodayGoalFailure('Failed to delete today goal: $e'));
      }
    });

    // 批量删除今日目标
    on<DeleteTodayGoalsByIdsEvent>((event, emit) async {
      try {
        await todayGoalRepository.deleteTodayGoalsByIds(event.goalIds);
        emit(TodayGoalsBatchDeleted(event.goalIds));
      } catch (e) {
        emit(TodayGoalFailure('Failed to delete today goals: $e'));
      }
    });
  }
}